<?php

namespace Renshan\DetectorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Renshan\Http\Request as CRequest;
use RenshanHttp\Response as CResponse;

class DetectController extends Controller
{
    public function targetFrontAction($id)
    {
        $em  = $this->get('doctrine')->getManager();
        $rep = $em->getRepository('Renshan\DetectorBundle\Entity\Target'); 

        $target = $rep->find($id);

        if ($target == null) {
            throw $this->createNotFoundException('接口不存在!');
        }

        return $this->render('RenshanDetectorBundle:Detect:target.html.twig', ['target' => $target]);
    }

    /**
     * 探测单个接口的ACTION
     *
     * @param integer $id   由路由自动注入
     *
     * @return Response
     */
    public function targetAction($id)
    {
        $ret = $this->get('renshan_detector.target')->detect($id);

        $response = new Response(json_encode($ret));
        $response->headers->set('content-type', 'application/json');
        $response->headers->set('Access-Control-Allow-Origin', 'http://localhost:3000');
        $response->headers->set('Access-Control-Allow-Credentials', "true");

        return $response;
    }

    public function groupFrontAction($id)
    {
        $em  = $this->get('doctrine')->getManager();
        $rep = $em->getRepository('Renshan\DetectorBundle\Entity\ReqGroup');

        $group = $rep->find($id);

        if ($group == null || $group->getUser()->getId() !== $this->getUser()->getId()) {
            throw $this->createNotFoundException("分组不存在");
        }

        return $this->render('RenshanDetectorBundle:Detect:group.html.twig', ['group' => $group, 'targets' => $group->getTargets()]);
    }

    /**
     * 探测单个接口的ACTION
     *
     * @param integer $id   由路由自动注入
     *
     * @return Response
     */
    public function groupAction($id)
    {
        $ret = $this->get('renshan_detector.group')->detect();

        $response = new Response(json_encode($ret));
        $response->headers->set('content-type', 'application/json');
        $response->headers->set('Access-Control-Allow-Origin', 'http://localhost:3000');
        $response->headers->set('Access-Control-Allow-Credentials', "true");

        return $response;
    }
}
